#ifndef xpack_lang_cxx_index_of_first
#define xpack_lang_cxx_index_of_first
#pragma push_macro("xuser")
#undef  xuser
#define xuser mixc::lang_cxx::inc
#include"define/base_type.hpp"
#include"lang/cxx.hpp"
#pragma pop_macro("xuser")

namespace mixc::lang_cxx{
    cxx_index_pair index_of_first_core(auto main, auto pattern, auto const & compare) {
        auto result          = cxx_index_pair{};
        result->i_main       = not_exist;
        result->i_pattern    = not_exist;

        for(uxx i = 0, length = main->length; i < length; i++){
            for(uxx j = 0, length = pattern->length; j < length; j++){
                // 约定:
                // left 为待匹配字符串的字符，right 为匹配参数字符
                if (compare(main[i], pattern[j]) == 0){
                    result->i_main = i;
                    result->i_pattern = j;
                    return result;
                }
            }
        }
        return result;
    }


    template<class item_t>
    template<class item_seq_t, class>
    inline cxx_index_pair cxx<item_t>::index_of_first(item_seq_t const & value, invoke_compare_t compare) const {
        return index_of_first_core(xthe, inc::unified_seq<item_seq_t>(value), compare);
    }

    template<class item_t>
    inline uxx cxx<item_t>::index_of_first(item_cref_t value, invoke_compare_t compare) const {
        for(uxx i = 0, length = xthe->length; i < length; i++){
            // 约定:
            // left 为待匹配字符串的字符，right 为匹配参数字符
            if (compare(xthe[i], value) == 0){
                return i;
            }
        }
        return not_exist;
    }

    template<class item_t>
    inline uxx cxx<item_t>::index_of_first(the_cref_t value, invoke_compare_t compare) const {
        the_t origin    = xthe;
        uxx   miss      = 0;
        uxx   index     = 0;

        if (origin->length < value->length or value->length == zero) {
            return not_exist;
        }
        while(true){
            // 寻找第一个不匹配的字符
            if (index = origin.index_of_first(value[miss], compare); 
                index == not_exist){
                break;
            }
            // 如果 miss < index，就等价 origin.backward() 后移
            if (origin = origin.forward(miss - index); origin->length < value->length) {
                break;
            }
            for(index = 0; ; index++){
                if (index == value->length) {
                    return uxx((item_t *)(origin) - (item_t *)(xthe));
                }

                // 约定:
                // left 为待匹配字符串的字符，right 为匹配参数字符
                if (compare(origin[index], value[index]) != 0) {
                    // 从 miss 之后一个字符（miss 这个位置已经不匹配了，没理由还从这个位置匹配）开始找当前 miss 的字符，
                    // 如果找到了就从头开始匹配字符串
                    miss = index; // 先
                    origin = origin.backward(miss + 1); // 后
                    break;
                }
            }
        }
        return not_exist;
    }
}

#endif
